#!/usr/bin/python

import sys

sys.path.append("/home/dingjun/source/wsgiserver")
import get_info
import MySQLdb
import time

if __name__ == "__main__":
    db_host= "localhost"
    db_user="opensips"
    db_pw = "opensipsrw."
    db_name = "data_collection"


    now = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    cpu_t = None
    mem_t = None
    net_t = None
    sys_t = None
    turn_t = None
    user_t = None
    cpu = 0
    mem = 0
    rx = 0
    tx =0
    load = 0
    turn = 0
    user = 0

    mod = __import__(__name__)
    #print mod

    maps = [
        ("cpu_t",get_info.get_cpu_usage),
        ("mem_t",get_info.get_mem_usage),
        ("net_t",get_info.get_net_traffic),
        ("sys_t",get_info.get_load),
        ("turn_t",get_info.get_turn_user),
        ("user_t",get_info.get_user_status)
    ]
    for k,v in maps:
        #print k,v
        setattr(mod, k,  get_info.spawn(v))
        getattr(mod,k).start()

    #print cpu_t,mem_t,getattr(mod, "cpu_t"),getattr(mod,"mem_t")
    #print "begin to join"
    for k,v in maps:
        #print k
        a = getattr(mod,k)
        #print a
        a.join()
    for k,v in [
            ("cpu", "cpu_t"),("mem", "mem_t"), #(("rx","tx"),"net_t"),
            ("load", "sys_t"), ("turn", "turn_t"), ("user", "user_t")]:
        #print k,v
        setattr(mod, k, getattr(mod,v).value)
        #getattr(mod,k) = getattr(mod,v).value
    rx,tx=net_t.value
    #cpu,mem,(rx,tx),load,turn = get_info.get_cpu_usage(),get_info.get_mem_usage(),get_info.get_net_traffic(),get_info.get_load(),get_info.get_turn_user()
    #print cpu,mem,rx,tx,load,turn
    sips=get_info.get_user_status()
    #print sips

    conn=MySQLdb.connect(db_host,db_user,db_pw,db_name)
    cur=conn.cursor()
    try:
        sql="insert into sys_status(r_time, cpu, mem, rx, tx,  sys_load, turn) \
                values('%s', %.2f,%.2f, %.2f, %.2f, %.2f, %d)" % (
                        now,
                        cpu, mem,rx,tx,load,turn)

        #print sql
        cur.execute(sql)
        for k in sips.keys():
            sql1="insert into user_status(r_time, user_num, vendor_name, phone_num,dev_num) \
                    values('%s', %d, '%s', %d, %d)" % (
                            now,
                            sips[k]["num"],
                            k,
                            sips[k]["phone"],
                            sips[k]["dev"]
                            )
            #print sql1
            cur.execute(sql1)
    finally:
        conn.commit()
        cur.close()
        conn.close()
